package com.example.wxsmart.interceptor;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.example.wxsmart.pojo.User;
import com.example.wxsmart.util.JwtUtil;
import com.example.wxsmart.util.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author Luojunxian
 * @data 2022/8/4 11:50
 * @classname LoginInterceptor
 */
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    /**
     * Controller之前
     *
     * @param request  请求
     * @param response 响应
     * @param handler  处理程序
     * @return boolean
     * @throws Exception 异常
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Result<Object> result;

        String token = request.getHeader("token");

        if (StringUtils.checkValNotNull(token)) {
            User user = JwtUtil.checkToken(token);
            if (user != null) {
                log.info("token:{}校验成功,用户:{}", token, user.getName());
                return true;
            } else {
                log.info("token:{}解析失败...", token);
                result = Result.fail("token解析失败...");
            }
        } else {
            result = Result.fail("token为空...");
        }

        response.setContentType("application/json; charset=UTF-8");
        response.getWriter().write(JSON.toJSONString(result));

        return false;
    }

    /**
     * 方法体后,页面渲染之前
     *
     * @param request      请求
     * @param response     响应
     * @param handler      处理程序
     * @param modelAndView 模型和视图
     * @throws Exception 异常
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    /**
     * 页面渲染之后
     *
     * @param request  请求
     * @param response 响应
     * @param handler  处理程序
     * @param ex       ex
     * @throws Exception 异常
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
